package com.he.heblog.controller;
import com.he.heblog.dto.UserDto;
import com.he.heblog.entity.User;
import com.he.heblog.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

/*文件上传下载*/
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
@Value("${heBlog.path}")
String bathPath;
@Autowired
UserService userService;
//上传图片和头像
@PostMapping("upload/{isAvatar}")
public HashMap<String, String> upload(MultipartFile file, @PathVariable Boolean isAvatar){


//file是一个临时文件，需要转储到指定位置，否则这次请求后就会消失
    try {
        String path;
        if(isAvatar) {
          path = bathPath + "avatar/";
        }
        else {
         path=bathPath + "topicPicture/";
        }
//上传文件的原始名字
        String originalFilename = file.getOriginalFilename();
// 截取文件名后缀
        String profileSuffix= originalFilename.substring(originalFilename.lastIndexOf("."));
//使用UUID重新生成文件名，防止文件名重复或覆盖
        String UUIDName = UUID.randomUUID().toString()+profileSuffix;
// 判断当前保存路径是否存在，没有则创建一个
        File dir=new File(path);
        if(!dir.exists()) {
            dir.mkdirs();
        }
        file.transferTo(new File(path+UUIDName));
//        上传用户头像可以直接获取当前登录用户保存到数据库中
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDto principal = (UserDto) authentication.getPrincipal();
        Integer id = principal.getId();
        User user = new User();
        user.setId(id);
        user.setAvatar(UUIDName);
        userService.updateById(user);
//        更新session中的用户信息
        principal.setAvatar(UUIDName);
        HashMap<String, String> result = new HashMap<>();
        result.put("code","200");
        result.put("msg","上传成功");
        result.put("data",UUIDName);
        return result;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}
@GetMapping("/download/{fileLocation}/{name}")
public void download(@PathVariable String name,@PathVariable String fileLocation, HttpServletResponse response) {

    try {
        String path=bathPath+fileLocation+"/";
        //通过输入流本地读取数据
        FileInputStream inputStream=new FileInputStream(new File(path+name));
       //通过输出流向客户端输出数据
        ServletOutputStream outputStream = response.getOutputStream();
       //指定返回类型
        response.setContentType("image/jpeg");
        int len=0;
       byte[] bytes=new byte[1024];
        while ((len=inputStream.read(bytes))!=-1) {
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}


}
